'''
工程优化实际问题
'''
import numpy as np

'''
压力容器设计
'''


def pressure_vessel(X):
    x1 = X[0]  # Ts
    x2 = X[1]  # Th
    x3 = X[2]  # R
    x4 = X[3]  # L

    # 约束条件
    g1 = -x1 + 0.0193 * x3
    g2 = -x2 + 0.00954 * x3
    g3 = -np.math.pi * x3 ** 2 - 4 * np.math.pi * x3 ** 3 / 3 + 1296000
    g4 = x4 - 240

    if g1 <= 0 and g2 <= 0 and g3 <= 0 and g4 <= 0:
        # 若满足约束条件，则计算适应度值
        fitness = 0.6224 * x1 * x3 * x4 + 1.7781 * x2 * x3 ** 2 + 3.1661 * x1 ** 2 * x4 + 19.84 * x1 ** 2 * x3
    else:
        # 若不满足约束条件，则将适应值设置为一个很大的惩罚数
        fitness = 10E32

    return fitness


'''
三杆桁架设计
'''


def three_bar_truss(X):
    x1 = X[0]
    x2 = X[1]
    l = 100
    P = 2
    sigma = 2

    # 约束条件判断
    g1 = (np.sqrt(2) * x1 + x2) * P / (np.sqrt(2) * x1 ** 2 + 2 * x1 * x2) - sigma
    g2 = x2 * P / (np.sqrt(2) * x1 ** 2 + 2 * x1 * x2) - sigma
    g3 = P / (np.sqrt(2) * x2 + x1) - sigma

    if g1 <= 0 and g2 <= 0 and g3 <= 0:
        # 满足约束
        fitness = (2 * np.sqrt(2) * x1 + x2) * l
    else:
        # 不满足
        fitness = 10E32

    return fitness


'''
拉压弹簧设计
'''


def spring_fun(X):
    x1 = X[0]
    x2 = X[1]
    x3 = X[2]

    # 约束条件判断
    g1 = 1 - (x2 ** 3 * x3) / (71785 * x1 ** 4)
    g2 = (4 * x2 ** 2 - x1 * x2) / (12566 * (x2 * x1 ** 3 - x1 ** 4)) + 1 / (5108 * x1 ** 2) - 1
    g3 = 1 - (140.45 * x1) / (x2 ** 2 * x3)
    g4 = (x1 + x2) / 1.5 - 1

    if g1 <= 0 and g2 <= 0 and g3 <= 0 and g4 <= 0:
        # 满足约束条件
        fitness = (x3 + 2) * x2 * x1 ** 2
    else:
        fitness = 10E32

    return fitness
